﻿Imports ICSharpCode.SharpZipLib.Zip
Imports System.IO

Public Class ZipExtract

    ''' <summary>Extracts the specified zip file with its directory hierarchy</summary>
    ''' <param name="SourceFileName">Zip file to be extracted</param>
    ''' <param name="DestinationFolderName">New folder that the zip will be extracted into</param>
    ''' <param name="DeleteZip">Delete or keep the original zip after extracting</param>
    Public Shared Sub Extract(ByVal SourceFileName As String, _
                              ByVal DestinationFolderName As String, _
                              Optional ByVal DeleteZip As Boolean = False)

        Try

            Using ZIS As New ZipInputStream(File.OpenRead(SourceFileName))

                Dim ZE As ZipEntry = ZIS.GetNextEntry()

                While Not IsNothing(ZE)

                    Dim strDirectoryName As String = Path.GetDirectoryName(ZE.Name)
                    Dim strFileName As String = Path.GetFileName(ZE.Name)

                    'Check for any folder existency in the zip folder
                    If strDirectoryName.Length > 0 Then
                        Directory.CreateDirectory(DestinationFolderName & "\" & strDirectoryName)
                    End If

                    If strFileName <> [String].Empty Then

                        Using FS As FileStream = File.Create(DestinationFolderName & "\" & ZE.Name)

                            Dim i As Integer = 2048
                            Dim b As Byte() = New Byte(2048) {}

                            While True

                                i = ZIS.Read(b, 0, b.Length)

                                If i > 0 Then
                                    FS.Write(b, 0, i)
                                Else
                                    Exit While
                                End If

                            End While

                        End Using

                    End If

                    ZE = ZIS.GetNextEntry()

                End While

            End Using

        Catch ex As ExecutionEngineException

            Throw ex

        End Try

        'Delete the original zip file after extracting it
        If DeleteZip = True Then
            File.Delete(SourceFileName)
        End If

    End Sub


End Class
